import { nextTick } from "vue";
import type { EChartsOption } from "echarts";
import dayjs from "dayjs";
import { formatMissingData } from "@/utils/common";

// const formatDataFn = (data: Array<any>): Array<any> => {
//   let value = data.find(item => item.value).value;
//   return data.map(item => {
//     if (!item.value) {
//       item.value = value;
//     } else {
//       value = item.value;
//     }
//     return item;
//   });
// };

export const getSingleLineSeries = (code?: string, val = undefined, specColor: Array<any> = [], data: Array<any> = []): Record<string, any> => {
  const type = "line";
  let name = code;
  let symbol = "none";
  let showSymbol = false;
  let color, itemStyle, endLabel, lineStyle;
  if (!val && !specColor?.length) {
    symbol = "circle";
    showSymbol = true;
    color = "#3B82F6";
    itemStyle = {
      color
    };
    endLabel = {
      show: false
    };
    lineStyle = {
      color,
      width: 1
    };
  } else {
    const len = data?.length;
    name = name?.toUpperCase();
    data = [];
    let num = 0;
    do {
      data.push(val);
      num++;
    } while (num < len);
    color = specColor.find(item => item.code === `${code}Color`)?.colorValue || undefined;
    endLabel = {
      show: true,
      color,
      formatter: "{a}: {c}"
    };
    lineStyle = {
      color,
      width: 1,
      type: "dashed"
    };
  }
  return { name, type, symbol, showSymbol, itemStyle, data, endLabel, lineStyle };
};

export const getEchartsLineSeries = (
  type?: "up" | "down" | "target" | "actual",
  title?: string,
  seriesMetaData?: Record<string, any>
): Array<any> => {
  const {
    // name = "",
    data = [],
    uslValue = undefined,
    uclValue = undefined,
    uwlValue = undefined,
    targetValue = undefined,
    lwlValue = undefined,
    lclValue = undefined,
    lslValue = undefined,
    specColor = []
  } = seriesMetaData;
  const ss: Array<any> = [];
  if (type === "up") {
    if (typeof uslValue === "number") {
      const s = getSingleLineSeries("usl", uslValue, specColor, data);
      ss.push(s);
    }
    if (typeof uclValue === "number") {
      const s = getSingleLineSeries("ucl", uclValue, specColor, data);
      ss.push(s);
    }
    if (typeof uwlValue === "number") {
      const s = getSingleLineSeries("uwl", uwlValue, specColor, data);
      ss.push(s);
    }
  } else if (type === "down") {
    if (typeof lwlValue === "number") {
      const s = getSingleLineSeries("lwl", lwlValue, specColor, data);
      ss.push(s);
    }
    if (typeof lclValue === "number") {
      const s = getSingleLineSeries("lcl", lclValue, specColor, data);
      ss.push(s);
    }
    if (typeof lslValue === "number") {
      const s = getSingleLineSeries("lsl", lslValue, specColor, data);
      ss.push(s);
    }
  } else if (type === "target") {
    const s = getSingleLineSeries("target", targetValue, specColor, data);
    ss.push(s);
  } else if (type === "actual") {
    // 表头是否用具体点位指标名称
    // const ac = getSingleLineSeries(name, undefined, null, data);
    const ac = getSingleLineSeries(title, undefined, undefined, data);
    ss.push(ac);
  }
  return ss;
};

export const farmatLineData = (metaData: Record<string, any>): Record<string, any> => {
  if (!metaData) {
    metaData = {};
  }
  let {
    indicatorName: name = "",
    pointValues = [],
    startValue: min = undefined,
    step: interval = undefined,
    uslValue = undefined,
    uclValue = undefined,
    uwlValue = undefined,
    targetValue = undefined,
    lwlValue = undefined,
    lclValue = undefined,
    lslValue = undefined,
    specColor = [
      {
        code: "uslColor",
        colorValue: "#FF0000"
      },
      {
        code: "uclColor",
        colorValue: "#A600FF"
      },
      {
        code: "uwlColor",
        colorValue: "#FF9900"
      },
      {
        code: "targetColor",
        colorValue: "#00E272"
      },
      {
        code: "lwlColor",
        colorValue: "#FF9900"
      },
      {
        code: "lclColor",
        colorValue: "#A600FF"
      },
      {
        code: "lslColor",
        colorValue: "#FF0000"
      }
    ]
  } = metaData;
  // pointValues = formatDataFn(pointValues);
  // const data = pointValues?.map(item => item?.value);
  const data = formatMissingData(pointValues?.map(item => item?.value));
  const xAxisData = pointValues.map(item => dayjs(item.time).format("HH:mm"));
  return { name, data, xAxisData, min, interval, uslValue, uclValue, uwlValue, targetValue, lwlValue, lclValue, lslValue, specColor };
  // 调试
  // return {
  //   name,
  //   data,
  //   xAxisData,
  //   min,
  //   interval,
  //   uslValue: 110,
  //   uclValue: 100,
  //   uwlValue: 90,
  //   targetValue: 60,
  //   lwlValue: 50,
  //   lclValue: 40,
  //   lslValue: 30,
  //   specColor
  // };
};

export const farmatLineData2 = (metaData: Record<string, any>): Record<string, any> => {
  if (!metaData) {
    metaData = { hourValueList: [], querySpcIndicatorDetailRespDTO: {} };
  }
  let { hourValueList = [], querySpcIndicatorDetailRespDTO = {} } = metaData;
  if (!hourValueList?.length) {
    hourValueList = [];
  }
  if (!querySpcIndicatorDetailRespDTO) {
    querySpcIndicatorDetailRespDTO = {};
  }
  const data = hourValueList.map(item => item?.value);
  const xAxisData = hourValueList.map(item => item?.hourStr);
  const {
    indicatorName: name = "",
    startValue: min = undefined,
    step: interval = undefined,
    uslValue = undefined,
    uclValue = undefined,
    uwlValue = undefined,
    targetValue = undefined,
    lwlValue = undefined,
    lclValue = undefined,
    lslValue = undefined,
    specColor = [
      {
        code: "uslColor",
        colorValue: "#A600FF"
      },
      {
        code: "uclColor",
        colorValue: "#FF0000"
      },
      {
        code: "uwlColor",
        colorValue: "#FF9900"
      },
      {
        code: "targetColor",
        colorValue: "#00E272"
      },
      {
        code: "lwlColor",
        colorValue: "#FF9900"
      },
      {
        code: "lclColor",
        colorValue: "#FF0000"
      },
      {
        code: "lslColor",
        colorValue: "#A600FF"
      }
    ]
  } = querySpcIndicatorDetailRespDTO;
  return { name, data, xAxisData, min, interval, uslValue, uclValue, uwlValue, targetValue, lwlValue, lclValue, lslValue, specColor };
  // 调试
  // return {
  //   name,
  //   data,
  //   xAxisData,
  //   min,
  //   interval,
  //   uslValue: 110,
  //   uclValue: 100,
  //   uwlValue: 90,
  //   targetValue: 60,
  //   lwlValue: 50,
  //   lclValue: 40,
  //   lslValue: 30,
  //   specColor
  // };
};

const farmatLineData3 = (metaData: Array<any>): Record<string, any> => {
  const data = metaData?.map(item => item?.value);
  const xAxisData = metaData?.map(item => `${item.hourStr}:00`);
  return { data, xAxisData };
};

const farmatLineData4 = (metaData: Array<any>): Record<string, any> => {
  const data = metaData?.map(item => item?.value);
  const xAxisData = metaData?.map(item => item.eqpId);
  return { data, xAxisData };
};

export const useInitLineEcharts = (
  type: 0 | 1 | 2 | 3, //  0 line   1 line-water   2 line-oneDay   3 line-oneDay-area
  controlLine: Array<string> = [],
  title?: string,
  unit?: string,
  data?: Record<string, any> | Array<any>,
  cb?: (o: EChartsOption) => void
) => {
  let seriesMetaData;
  switch (type) {
    case 0:
      seriesMetaData = farmatLineData(data);
      break;
    case 1:
      seriesMetaData = farmatLineData2(data);
      break;
    case 2:
      seriesMetaData = farmatLineData3(data as Array<any>);
      break;
    case 3:
      seriesMetaData = farmatLineData4(data as Array<any>);
      break;
  }
  const { xAxisData = [], min = undefined, interval = undefined, targetValue = undefined } = seriesMetaData;
  const animation = false;
  const grid = {
    top: unit ? 32 : 12,
    bottom: 0,
    left: 12,
    right: 16,
    containLabel: true
  };
  const tooltip = {
    show: true,
    trigger: "axis",
    formatter: `${title} <br/> {b} : {c}${unit ?? ""}`
  };
  const xAxis = {
    type: "category",
    splitLine: {
      show: true
    },
    boundaryGap: false,
    data: xAxisData
  };
  const yAxis = {
    // nameTextStyle: {
    //   align: "left"
    // },
    type: "value",
    name: unit ? `单位：${unit}` : undefined,
    splitLine: {
      show: true
    }
    // min,
    // interval
  };
  const series: Array<any> = [];
  if (controlLine.includes("up")) {
    const s = getEchartsLineSeries("up", title, seriesMetaData);
    series.push(...s);
  }
  if (controlLine.includes("down")) {
    const s = getEchartsLineSeries("down", title, seriesMetaData);
    series.push(...s);
  }
  if (typeof targetValue === "number") {
    const t = getEchartsLineSeries("target", title, seriesMetaData);
    series.push(...t);
  }
  const ac = getEchartsLineSeries("actual", title, seriesMetaData);
  series.push(...ac);
  cb && cb({ animation, grid, tooltip, xAxis, yAxis, series } as EChartsOption);
};

const formatPieData = (flag: boolean = false, name: string = "", data: Array<Record<string, any>>) => {
  if (flag) {
    switch (name) {
      case "今日机台状态统计":
        return data.map((item: any) => ({ ...item, value: item.num, name: item.eqpStatus }));
      case "今日机台保养任务":
        return data.map((item: any) => ({ ...item, value: item.num, name: item.pmStatusName }));
      case "今日机台维修任务":
        return data.map((item: any) => ({ ...item, value: item.num, name: item.deviceMaintainName }));
      case "今日机台异常告警":
        return data.map((item: any) => ({ ...item, value: item.num, name: item.alarmStatusName }));
    }
  } else {
    switch (name) {
      case "机台数量统计":
        return data.map((item: any) => ({ ...item, value: item.num, name: item.distributeName }));
      default:
        return data.map((item: any) => ({ ...item, value: item.num, name: item.areaCode }));
    }
  }
};

export const useInitPieEcharts = async (
  el: ComponentInternalInstance,
  flag: boolean = false,
  name: string,
  metaData: Array<Record<string, any>>,
  unit: string,
  cb: (o: EChartsOption) => void
) => {
  await nextTick();
  const ec = await el?.getEcharts();
  if (!ec) return null;
  const { getWidth = null } = ec;
  const labelLayout = function (params) {
    if (!getWidth) return null;
    const isLeft = params.labelRect.x < getWidth() / 2;
    const points = params.labelLinePoints;
    points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
    return { labelLinePoints: points };
  };
  const data = formatPieData(flag, name, metaData);
  // const title = {
  //   text: `今日机台\n${name}`,
  //   textStyle: {
  //     color: "#555",
  //     fontSize: 14,
  //     fontWeight: 600,
  //     lineHeight: 16
  //   },
  //   left: "center",
  //   top: "center"
  // };
  let radius;
  if (flag) {
    radius = ["30%", "52%"];
  } else {
    radius = "52%";
  }
  const options: EChartsOption = {
    tooltip: {
      trigger: "item",
      formatter: `{a} <br/>{b} : {c}${unit ?? ""} ({d}%)`
    },
    grid: {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0,
      containLabel: true
    },
    // toolbox: {
    //   show: true,
    //   feature: {
    //     saveAsImage: { show: true, title: "导出" }
    //   }
    // },
    series: [
      {
        name: flag ? `${name}` : name,
        type: "pie",
        radius,
        center: ["50%", "50%"],
        minAngle: 4,
        avoidLabelOverlap: true,
        label: {
          // alignTo: "edge",
          formatter: `{name|{b}}\n{num|{c}${unit ?? ""}}{percent| ( {d}% )}`,
          minMargin: 2,
          edgeDistance: "10%",
          lineHeight: 20,
          rich: {
            num: {
              fontSize: 12,
              color: "#222",
              lineHeight: 16,
              fontWeight: 600
            },
            percent: {
              fontSize: 10,
              color: "#333",
              lineHeight: 16
            }
          }
        },
        labelLine: {
          show: true,
          // length: 15,
          // length2: 0,
          maxSurfaceAngle: 85
        },
        labelLayout,
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        }
      }
    ]
  };
  // if (flag) {
  //   options["title"] = title;
  // }
  cb && cb(options);
};

const formatBarData = (flag: boolean = false, data: Array<Record<string, any>>) => {
  let xAxisData, seriesData;
  if (flag) {
    xAxisData = data.map(item => item?.className);
    seriesData = data.map(item => {
      const value = item.num;
      let color = "";
      switch (item.classCode) {
        case "ELECTRICTITY":
          color = "#5B8FF9";
          break;
        case "GAS":
          color = "#F6BD16";
          break;
        case "MACHINE":
          color = "#5D7092";
          break;
        case "WATER":
          color = "#5AD8A6";
          break;
        default:
          color = "#5B8FF9";
          break;
      }
      const itemStyle = { color };
      return { ...item, value, itemStyle };
    });
  } else {
    // xAxisData = data.map(item => item?.dayStr);
    xAxisData = data.map(item => dayjs(item?.dayStr).format("MM/DD"));
    seriesData = data.map((item, index, arr) => {
      if (index === arr.length - 1) {
        item["itemStyle"] = { color: "#28D892" };
      } else {
        item["itemStyle"] = { color: "#FFC200" };
      }
      return item;
    });
  }
  return { xAxisData, seriesData };
};

export const useInitBarEcharts = (
  flag: boolean = false,
  flag2: boolean = false,
  title: string,
  data: Array<Record<string, any>>,
  unit?: string,
  cb?: (o: EChartsOption) => void
) => {
  const { xAxisData, seriesData } = formatBarData(flag, data);
  const grid = {
    top: unit ? 32 : 12,
    bottom: 0,
    left: 12,
    right: 12,
    containLabel: true
  };
  const tooltip = {
    show: true,
    trigger: "axis",
    formatter: `${title} <br/> {b} : {c}${unit ?? ""}`,
    axisPointer: flag2
      ? {
          type: "shadow",
          shadowStyle: {
            color: "transparent"
          }
        }
      : undefined
  };

  // const toolbox = {
  //   show: true,
  //   feature: {
  //     saveAsImage: { show: true, title: "导出" }
  //   }
  // };
  const xAxis = [
    {
      type: "category",
      data: xAxisData,
      axisPointer: {
        type: "shadow"
      }
    }
  ];
  const yAxis = [
    {
      type: "value",
      name: unit ? `单位：${unit}` : undefined
    }
  ];
  const series_bar = {
    type: "bar",
    data: seriesData,
    itemStyle: {
      normal: {
        label: {
          show: false,
          position: "top"
        }
      }
    },
    selectedMode: "single",
    select: flag2
      ? {
          itemStyle: {
            borderColor: "#D1D5DE",
            borderWidth: 4
          }
        }
      : undefined
  };
  const series_line = {
    type: "line",
    data: seriesData,
    symbol: "none",
    lineStyle: {
      color: "#3B82F6",
      width: 1
    }
  };
  const series = [series_bar];
  if (!flag) {
    series.push(series_line);
  }
  const options = { grid, tooltip, xAxis, yAxis, series };
  cb && cb(options as EChartsOption);
};
